require('./mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/**
  _id: 内嵌文档，不生成id
  name: 属性名称
  field: 属性字段
  dtype: 属性数据类型
  len: 属性值长度
  notnullable: 是否可空
  dvalue: 属性默认值
*/
var AttrSchema = Schema({
  _id: false,
  name: String,
  field: String,
  dtype: String,
  dvalue: Schema.Types.Mixed,
  len: { type: Number, default: 255 },
  notnullable: { type: Boolean, default: false }
});

/**
  src和dest关联的是模型
 */
var bizrelaSchema = Schema({
  type: { type: Schema.Types.ObjectId, ref: 'RelationType', required: true },
  src: { type: Schema.Types.ObjectId, ref: 'Bizdef', required: true },
  dest: { type: Schema.Types.ObjectId, ref: 'Bizdef', required: true },
  desc: { type: String },
  restrain: { type: String, default: 'onetoone', required: true, enum: ['onetoone', 'onetomany', 'manytomany', 'manytoone'] },
  attrs: [AttrSchema],
})

bizrelaSchema.statics = {
  init: function () {
  },
  page: function (query, page, limit, callback) {
    if (page === undefined) page = 0
    if (limit === undefined) limit = 20
    Bizrela.count(query).then(total => {
      Bizrela
        .find(query)
        .skip((page) * limit)
        .limit(limit * 1)
        .populate('type')
        .populate('src')
        .populate('dest')
        .exec((err, docs) => {
          callback({
            pageable: {
              totalElements: total,
              numberOfElements: docs.length,
              totalPages: Math.ceil(total / limit),
              number: page,
              first: page == 0,
              last: docs.length < limit || (docs.length === limit && (page + 1) * limit >= total),
              size: limit,
              fromNumber: page * limit,
              toNumber: page * limit + docs.length
            },
            docs
          })
        })
    })
  }
}

var Bizrela = mongoose.model('Bizrela', bizrelaSchema);

module.exports = Bizrela
